package org.batatasframework.support.loader;

import org.batatasframework.expression.ExpressionClause;
import org.batatasframework.properties.ProperitesGroup;
import org.batatasframework.properties.PropertiesDefine;
import org.batatasframework.properties.PropertiesName;
import org.batatasframework.support.database.TableInfo;
import org.batatasframework.support.database.jdbc.ConnectionAccessor;
import org.batatasframework.support.database.metadatas.DatabaseMetadataResource;
import org.batatasframework.support.database.metadatas.TableMetadata;
import org.batatasframework.support.factory.TableDefinitionRegistry;
import org.batatasframework.values.DelegateValueReader;
import org.batatasframework.values.ValueGetter;
import org.batatasframework.values.ValueReader;
import org.springframework.util.Assert;

public class DatabasePropertiesParser extends DelegateValueReader implements PropertiesDefine {
	
	private final ConnectionAccessor connectionAccessor;
	private final DatabaseMetadataResource databaseMetadataSources;
	private final TableDefinitionRegistry tableFactoryRegistry;
	
	private TableInfo tableInfo;
	private TableMetadata tableMetadata;
	
	private final PropertiesDefine block;
	
	public DatabasePropertiesParser(ConnectionAccessor connectionAccessor,
			DatabaseMetadataResource databaseMetadataSources,
			TableDefinitionRegistry tableFactoryRegistry,
			PropertiesDefine block) {
		this.block = block;
		
		this.connectionAccessor = connectionAccessor;
		this.databaseMetadataSources = databaseMetadataSources;
		this.tableFactoryRegistry = tableFactoryRegistry;
	}
	
	@Override
	protected ValueReader getSource() {
		return block;
	}
	
	@Override
	public PropertiesName getName() {
		return block.getName();
	}

	public void init() throws Exception{
		String schema  = block.getString("schema");
		String catalog = block.getString("catalog");
		String table   = block.getString("table");
		
		this.tableInfo = new TableInfo(schema, catalog, table);
		this.tableMetadata = databaseMetadataSources.loadTableMetadata(connectionAccessor, tableInfo);
		
		Assert.notNull(tableMetadata, "无法解析数据库信息：" + tableInfo.getTableName());
	}

	public ConnectionAccessor getConnectionAccessor() {
		return connectionAccessor;
	}

	public DatabaseMetadataResource getDatabaseMetadataSources() {
		return databaseMetadataSources;
	}

	public TableDefinitionRegistry getTableFactoryRegistry() {
		return tableFactoryRegistry;
	}

	@Override
	public ExpressionClause getExpression(String byname) {
		return block.getExpression(byname);
	}

	public TableMetadata getTableMetadata() {
		return tableMetadata;
	}
	
	public String getTableName(){
		return tableInfo.getTableName();
	}

	@Override
	public ProperitesGroup getGroup(String name) {
		return block.getGroup(name);
	}

	@Override
	public ValueGetter getValue(String byname) {
		return block.getValue(byname);
	}
}